package com.gxuwz.weather.api;

import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.AppSigner;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class Weather15dRequest {

    public interface Weather15dCallback {
        void onSuccess(JsonObject weatherData);
        void onError(String error);
    }

    public static void requestWeather(String city, final Weather15dCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String path = "http://getweather.api.bdymkt.com/lundear/weather15d";
                ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.GET, path);
                request.setCredentials("bd0695e091ee4f83a9e4739a5a6dd3d5", "c3e30f7501024ba1aa958007d6377769");

                request.addHeaderParameter("Content-Type", "application/json;charset=UTF-8");

                request.addQueryParameter("areaCn", city);
                request.addQueryParameter("areaCode", "");
                request.addQueryParameter("ip", "");
                request.addQueryParameter("lat", "");
                request.addQueryParameter("lng", "");

                ApiExplorerClient client = new ApiExplorerClient(new AppSigner());

                try {
                    ApiExplorerResponse response = client.sendRequest(request);
                    String result = response.getResult();
                    System.out.println("15d="+result);
                    JsonObject jsonResponse = JsonParser.parseString(result).getAsJsonObject();

                    if (callback != null) {
                        callback.onSuccess(jsonResponse);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (callback != null) {
                        callback.onError("Failed to fetch 15-day weather: " + e.getMessage());
                    }
                }
            }
        }).start();
    }
}
